package com.athena.pojo;

import com.athena.utils.HttpProtocolUtil;
import com.athena.utils.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: xiaoxiang.zhang
 * @Description:响应对象
 * @Date: Create in 12:01 上午 2020/3/26
 */
public class Response {

  private OutputStream outs;

  public Response(OutputStream outs) {
    this.outs = outs;
  }

  /**
   * @return void
   * @Author yuyz
   * @Description 向页面输出指定数据
   * @Date 12:26 上午 2020/3/26
   * @Param [content]
   */
  public void output(String content) throws IOException {
    outs.write(content.getBytes());
  }

  /**
   * @return void
   * @Author yuyz
   * @Description 向页面输出文件
   * @Date 12:27 上午 2020/3/26
   * @Param [path]
   */
  public void outputHTML(String path) throws Exception {
    //1.获取文件的绝对路径
    String absolutePath = StaticResourceUtil.getAbsolutePath(path);
    System.out.println("===============path: " + absolutePath);
    //2.获得静态资源文件对象
    File file = new File(absolutePath);
    if (file.exists() && file.isFile()) {
      //当文件存在并且为正真的文件时输出
      StaticResourceUtil.outputStaticResource(new FileInputStream(file), outs);
    } else {
      //否则输出文件不存在
      output(HttpProtocolUtil.getHttpHeader404());
    }
  }
}
